package me.lxw.blogsystem.servlet.admin;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import me.lxw.blogsystem.dao.ArticleDAO;
import me.lxw.blogsystem.domain.Article;
import me.lxw.blogsystem.domain.Category;
import me.lxw.blogsystem.domain.Page;

@WebServlet("/admin/articleList.do")
public class ArticleListServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
        IOException {
        // 获取分页参数
        String pageStr = request.getParameter("page");
        int pageNumber = 1;
        if (pageStr != null && !"".equals(pageStr)) {
            pageNumber = Integer.valueOf(pageStr);
        }
        // 实例化 ArticleDAO
        ArticleDAO articleDAO = new ArticleDAO();

        // 选择的类别
        String categoryIdStr = request.getParameter("categoryId");
        int categoryId = -1;
        if (categoryIdStr != null) {
            categoryId = Integer.valueOf(categoryIdStr);
        }
        // 输入的类型
        String title = request.getParameter("title");
        if (title == null) {
            title = "";
        }
        // 获取数据
        try {
            // 查询所有的分类
            List<Category> list = articleDAO.findAllCategory();
            request.setAttribute("categoryList", list);

            // 搜索参数回传
            request.setAttribute("categoryId", categoryId);
            request.setAttribute("title", title);

            // 查询数据
            Page<Article> page = articleDAO.findAllByPage(pageNumber, 6, categoryId, title);
            // 将数据保存request 请求域中
            request.setAttribute("articleList", page.getData());
            request.setAttribute("curPageNo", page.getPageNo());
            request.setAttribute("totalPageNo", page.getTotalPages());
            // 跳转到articleList.jsp
            request.getRequestDispatcher("/admin/articleList.jsp").forward(request, response);

        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

}
